package com.echo.util.jdbc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;


/**
 * 常规对字符串处理工具类
 * @author tangsixiang
 *
 */
public class StringUtil {

	/**
	 * <P>判断是否为NULL或空字符换</P>
	 * @param arg
	 * @return
	 */
	public static boolean isNullEmpty(String arg) {
		if(arg == null) {
			return true;
		}
		else if(arg.trim().equals("")) {
			return true;
		}else{
			return false;
		}
	}
 
	
 
	
	/**
	 * 保留两位小数不进行四舍五入
	 * @param passwd
	 * @return
	 * @throws Exception
	 */
	public static double doubleGetTwo(double number){
		return Math.floor(number*100)/100;
	}
	
	/**
	 * 采用正则表达 过滤SQL需要替换占位符
	 * @param source
	 */
	public static String[]  sqlPatternRender(String source){
		String newSql=source;
		StringBuffer sb =new StringBuffer("");
		Pattern p = Pattern.compile("(#\\{[^\\}]*\\})");  
		Matcher m = p.matcher(source);  
		while(m.find()){  
			String temp=m.group(1);
			sb.append(temp.replaceAll("\\}", "").replaceAll("#\\{", "")).append(";");
			newSql=newSql.replaceFirst(escapeExprSpecialWord(temp), "?");
			}
	     if(sb.length()>=1)
	return new String[]{newSql,sb.toString()};
	     else
		return  null;
	}
	/**
	 * 转义正则特殊字符 （$()*+.[]?\^{},|）
	 * 
	 * @param keyword
	 * @return 转义后字符串
	 */
	public static String escapeExprSpecialWord(String keyword) {
		if (StringUtils.isNotBlank(keyword)) {
			String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
			for (String key : fbsArr) {
				if (keyword.contains(key)) {
					keyword = keyword.replace(key, "\\" + key);
				}
			}
		}
		return keyword;
	}
	public static void main(String[] args) {
		 System.out.println(sqlPatternRender("12315 #{gagaId} nihaoma #{username} where = #{gagaId}"));
		System.out.println(matcherPatternEmail("tangsixiang@163.com"));
		System.out.println(matcherPatternMObile("824243234243"));
	}
	
	
	/**
	 * 邮箱正则表达式 检测
	 * @param emailStr
	 * @return
	 */
	public static boolean  matcherPatternEmail(String emailStr){
		//电子邮件    
		 String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";    
		 Pattern regex = Pattern.compile(check);  
		 Matcher matcher = regex.matcher(emailStr);    
		return matcher.matches(); 
	}
	
	/**
	 * 移动电话的检测
	 * @param emailStr
	 * @return
	 */
	public static boolean  matcherPatternMObile(String emailStr){
		Pattern regex = Pattern.compile("[0-9]*");  
		 Matcher matcher = regex.matcher(emailStr);    
		return matcher.matches(); 
	}
}
